package tgc.edu.tms.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import tgc.edu.tms.custom.CommonController;
import tgc.edu.tms.entity.Curriculum;
import tgc.edu.tms.entity.kcb;
import tgc.edu.tms.web.form.CurriculumForm;
import tgc.edu.tms.web.form.KcbFrom;

@Controller
@RequestMapping(value="/dictionary/kcb")
public class KcbController extends CommonController<kcb, Integer, KcbFrom>{

	
	@Override
	public Specification<kcb> buildSpec(KcbFrom form) {
		Specification<kcb> spec = new Specification<kcb>() {

			@Override
			public Predicate toPredicate(Root<kcb> root, CriteriaQuery<?> query,
					CriteriaBuilder criteriaBuilder) {
				List<Predicate> rules = new ArrayList<>();
				if (StringUtils.hasText(form.getKcmc())) {
					rules.add(criteriaBuilder.like(root.get("kcmc"), "%" + form.getKcmc() + "%"));
				}
				if (StringUtils.hasText(form.getKcdm())) {
					rules.add(criteriaBuilder.like(root.get("kcdm"), "%" + form.getKcdm() + "%"));
				}
				if (StringUtils.hasText(form.getSearch())) {
					Predicate like = criteriaBuilder.like(root.get("kcmc"), "%" + form.getSearch() + "%");
					Predicate like2 = criteriaBuilder.like(root.get("kcdm"), "%" + form.getSearch() + "%");
					Predicate or = criteriaBuilder.or(like, like2);
					rules.add(or);
				}
				return criteriaBuilder.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}
}
